﻿using System;
using System.Collections.Generic;
using System.Text;

namespace SerialPortDemo_03
{
    public class CRC
    {
        public static byte[] crc16(byte[] data)
        {
            byte[] temp = new byte[data.Length + 2];
            int xda, xdapoly;
            int i, j, xdabit;
            xda = 0xFFFF;
            xdapoly = 0xA001;
            for (i = 0; i < data.Length; i++)
            {
                xda ^= data[i];
                for (j = 0; j < 8; j++)
                {
                    xdabit = (int)(xda & 0x01);
                    xda >>= 1;
                    if (xdabit == 1)
                        xda ^= xdapoly;
                }
            }
            Array.Copy(data, 0, temp, 0, data.Length);
            temp[temp.Length - 2] = (byte)(xda & 0xFF);
            temp[temp.Length - 1] = (byte)(xda >> 8);
            return temp;
        }
    }
}
